<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="录入时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择录入时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          :disabled="checkTodayAddStatus"
          @click="handleAdd"
          v-hasPermi="['manage:physical:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:physical:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Switch"
          :disabled="!canCompare"
          @click="handleCompare"
          v-hasPermi="['manage:physical:list']"
        >身体比对</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:physical:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:physical:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="physicalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="physicalId" type="index" width="50" />
      <el-table-column label="身高" align="center" prop="physicalHeight">
        <template #default="scope">
          <span>{{ scope.row.physicalHeight }} cm</span>
        </template>
      </el-table-column>
      <el-table-column label="体重" align="center" prop="physicalWeight">
        <template #default="scope">
          <span>{{ scope.row.physicalWeight }} kg</span>
        </template>
      </el-table-column>
      <el-table-column label="BMI" align="center" prop="physicalBmi">
        <template #default="scope">
          <span>{{ scope.row.physicalBmi }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体脂率" align="center" prop="physicalFatPercent">
        <template #default="scope">
          <span>{{ scope.row.physicalFatPercent }} %</span>
        </template>
      </el-table-column>
      <el-table-column label="腰围" align="center" prop="physicalWaistline">
        <template #default="scope">
          <span>{{ scope.row.physicalWaistline }} cm</span>
        </template>
      </el-table-column>
      <el-table-column label="胸围" align="center" prop="physicalBust">
        <template #default="scope">
          <span>{{ scope.row.physicalBust }} cm</span>
        </template>
      </el-table-column>
      <el-table-column label="臀围" align="center" prop="physicalHips">
        <template #default="scope">
          <span>{{ scope.row.physicalHips }} cm</span>
        </template>
      </el-table-column>
      <el-table-column label="血糖" align="center" prop="bloodSugar">
        <template #default="scope">
          <span>{{ scope.row.bloodSugar }} mmol/L</span>
        </template>
      </el-table-column>
      <el-table-column label="腰臀比" align="center" prop="waistHipRadio" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:physical:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:physical:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改身体管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="physicalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="身高" prop="physicalHeight">
          <el-input v-model="form.physicalHeight" placeholder="请输入身高">
            <template #append>cm</template>
          </el-input>
        </el-form-item>
        <el-form-item label="体重" prop="physicalWeight">
          <el-input v-model="form.physicalWeight" placeholder="请输入体重">
            <template #append>kg</template>
          </el-input>
        </el-form-item>
        <el-form-item label="体脂率" prop="physicalFatPercent">
          <el-input v-model="form.physicalFatPercent" placeholder="请输入体脂率">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="腰围" prop="physicalWaistline">
          <el-input v-model="form.physicalWaistline" placeholder="请输入腰围">
            <template #append>cm</template>
          </el-input>
        </el-form-item>
        <el-form-item label="胸围" prop="physicalBust">
          <el-input v-model="form.physicalBust" placeholder="请输入胸围">
            <template #append>cm</template>
          </el-input>
        </el-form-item>
        <el-form-item label="臀围" prop="physicalHips">
          <el-input v-model="form.physicalHips" placeholder="请输入臀围">
            <template #append>cm</template>
          </el-input>
        </el-form-item>
        <el-form-item label="血糖" prop="bloodSugar">
          <el-input v-model="form.bloodSugar" placeholder="请输入血糖">
            <template #append>mmol/L</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 身体比对对话框 -->
    <el-dialog title="身体数据比对" v-model="compareVisible" width="60%">
      <div class="compare-container">
        <div class="compare-column">
          <div v-for="item in compareData" :key="item.label">{{ item.label }}: {{ item.value1 }}</div>
        </div>
        <div class="compare-column arrows">
          <div v-for="item in compareData" :key="item.label" :class="item.arrowClass">{{ item.arrow }}</div>
        </div>
        <div class="compare-column">
          <div v-for="item in compareData" :key="item.label">{{ item.label }}: {{ item.value2 }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Physical">
import { listPhysical, getPhysical, delPhysical, addPhysical, updatePhysical } from "@/api/manage/physical";

const { proxy } = getCurrentInstance();

const physicalList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const checkTodayAddStatus = ref(false);

const compareVisible = ref(false);
const canCompare = computed(() => ids.value.length === 2);
const compareData = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: null,
  },
  rules: {
    physicalHeight: [
      { required: true, message: "身高不能为空", trigger: "blur" }
    ],
    physicalWeight: [
      { required: true, message: "体重不能为空", trigger: "blur" }
    ],
    physicalFatPercent: [
      { required: true, message: "体脂率不能为空", trigger: "blur" }
    ],
    physicalWaistline: [
      { required: true, message: "腰围不能为空", trigger: "blur" }
    ],
    physicalBust: [
      { required: true, message: "胸围不能为空", trigger: "blur" }
    ],
    physicalHips: [
      { required: true, message: "臀围不能为空", trigger: "blur" }
    ],
    bloodSugar: [
      { required: true, message: "血糖不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询身体管理列表 */
function getList() {
  loading.value = true;
  listPhysical(queryParams.value).then(response => {
    physicalList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    physicalId: null,
    physicalHeight: null,
    physicalWeight: null,
    physicalFatPercent: null,
    physicalWaistline: null,
    physicalBust: null,
    physicalHips: null,
    bloodSugar: null,
    createTime: null,
    userId: null
  };
  proxy.resetForm("physicalRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.physicalId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加身体管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _physicalId = row.physicalId || ids.value
  getPhysical(_physicalId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改身体管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["physicalRef"].validate(valid => {
    if (valid) {
      if (form.value.physicalId != null) {
        updatePhysical(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPhysical(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          checkTodayData();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _physicalIds = row.physicalId || ids.value;
  // 将日期转化为xx年xx月xx日的格式
  const dateStr = new Date(row.createTime).toLocaleDateString()
  let str = dateStr.split('/');
  const date = str[0] + '年' + str[1] + '月' + str[2] + '日'
  const delName = _physicalIds.length >= 1 ? '选中的身体记录' : date + '的身体记录'
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function() {
    return delPhysical(_physicalIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
    checkTodayData();
  }).catch(() => {});
}

// 对比数据处理
function handleCompare() {
  if (ids.value.length !== 2) {
    proxy.$modal.msgError("请选择两行数据进行比对");
    return;
  }

  // 找到两条记录
  const selectedData = physicalList.value.filter(item => ids.value.includes(item.physicalId));
  
  // 根据createTime排序，确保较早的日期排在前面
  selectedData.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));

  const data1 = selectedData[0];
  const data2 = selectedData[1];

  const keys = ['physicalHeight', 'physicalWeight', 'physicalBmi', 'physicalFatPercent', 'physicalWaistline', 'physicalBust', 'physicalHips', 'bloodSugar'];
  const labels = {
    'physicalHeight': '身高', 
    'physicalWeight': '体重', 
    'physicalBmi': 'BMI', 
    'physicalFatPercent': '体脂率', 
    'physicalWaistline': '腰围', 
    'physicalBust': '胸围', 
    'physicalHips': '臀围', 
    'bloodSugar': '血糖'
  };

  compareData.value = keys.map(key => {
    const value1 = data1[key];
    const value2 = data2[key];
    let arrow = '';
    let arrowClass = '';

    if (value1 !== value2) {
      arrow = value1 < value2 ? '↑' : '↓';
      arrowClass = value1 < value2 ? 'arrow-up' : 'arrow-down';
    }

    // 添加单位
    const unit = 
      key.includes('Height') || key.includes('Waistline') || key.includes('Bust') || key.includes('Hips') ? ' cm' :
      key.includes('Weight') ? ' kg' :
      key.includes('FatPercent') ? ' %' :
      key.includes('Sugar') ? ' mmol/L' : '';

    return {
      label: labels[key],
      value1: `${value1}${unit}`,
      value2: `${value2}${unit}`,
      arrow: arrow,
      arrowClass: arrowClass
    };
  });

  compareVisible.value = true;
}

// 查询今日是否已经提交过数据
function checkTodayData() {
  const now = new Date()
  const data = {}
  data.createTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()
  listPhysical(data).then(response => {
    checkTodayAddStatus.value = response.rows.length > 0
  })
}

getList();
checkTodayData();
</script>

<style lang='scss' scoped>
.compare-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  gap: 20px;
}

.compare-column {
  width: 35%;
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.compare-column div {
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  height: 40px;  // 添加固定高度
  align-items: center;  // 添加垂直居中
}

.compare-column div:last-child {
  border-bottom: none;
}

.arrows {
  width: 10%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;  // 修改为flex-start
  align-items: center;
  padding-top: 10px;  // 添加顶部padding
}

.arrows div {
  height: 40px;  // 与数据行高度一致
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

.arrow-up {
  color: #67c23a;
}

.arrow-down {
  color: #f56c6c;
}
</style>






